package com.puyuba.puyuba.view.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebStorage;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.puyuba.puyuba.MultiDexApplication;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.puyuba.puyuba.utils.MyJavascriptInterface;
import com.pyb.java.basemodule.BaseActivity;
import com.pyb.java.commonutil.utils.NetUtil;
import com.pyb.java.commonutil.ToastHelper;

import com.pyb.java.commonutil.widgets.X5WebView;
import com.pyb.java.network.NetBaseApi;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * create by gzy
 * 2020-12-03
 */
public class MainWebActivity extends BaseActivity {
    public static void startMainWebActivity(Context context, String url, String title) {
        Intent intent = new Intent(context, MainWebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    private X5WebView regisetWv;
    private RelativeLayout rlTitle;
    private LinearLayout llNetworkFailed;
    private TextView tvRefresh;
    private TextView tvTitle;

    Uri imageUri;
    ValueCallback mUploadMessage;
    ValueCallback mUploadCallbackAboveL;

    int PHOTO_REQUEST = 1;
    int VIDEO_REQUEST = 2;
    //获取相机 相册权限
    int REQUEST_CODED = 1;
    //保存图片请求权限
    int REQUEST_CODED_SAVE_IMG = 10;
    //保存图片的图片源
    String mBase64DataStr;

    String referer = NetBaseApi.getBaseUrl();
    boolean firstVisitWXH5PayUrl = true;
    String return_url = "";
    boolean isToPay;
    //音频管理
    AudioManager audioManager;
    AudioManager.OnAudioFocusChangeListener listener;
    private ImageView ivBack;
    private final static int SHUAXIN = 5;


    @Override
    public int getLayoutId() {
        return R.layout.activity_mainweb;
    }

    @Override
    protected void initView() {
        super.initView();

        //这个对宿主没什么影响，建议声明  x5 浏览器视频播放要注意 避免闪屏和透明问题
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvRefresh = (TextView) findViewById(R.id.tv_refresh);
        llNetworkFailed = (LinearLayout) findViewById(R.id.ll_network_failed);
        rlTitle = (RelativeLayout) findViewById(R.id.rl_title);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        regisetWv   = new X5WebView(this, null);
        if (regisetWv.getX5WebViewExtension() != null) {
            Bundle data = new Bundle();

            data.putBoolean("standardFullScreen", false);// true表示标准全屏，会调起onShowCustomView()，false表示X5全屏；不设置默认false，

            data.putBoolean("supportLiteWnd", false);// false：关闭小窗；true：开启小窗；不设置默认true，

            data.putInt("DefaultVideoScreen", 2);// 1：以页面内开始播放，2：以全屏开始播放；不设置默认：1

            regisetWv.getX5WebViewExtension().invokeMiscMethod("setVideoParams",
                    data);
            Bundle data2 = new Bundle();

            //val为true或false。  实现自动播放
            data2.putBoolean("require", true);
            regisetWv.getX5WebViewExtension().invokeMiscMethod("setVideoPlaybackRequiresUserGesture", data2);
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvTitle.setText(getIntent().getStringExtra("title") == null ? "考友之家" : getIntent().getStringExtra("title"));

        regisetWv.addJavascriptInterface(new JSInterestInterface(), "JSInterestInterface");
        regisetWv.removeJavascriptInterface("searchBoxJavaBridge_");
        regisetWv.removeJavascriptInterface("accessibility");
        regisetWv.removeJavascriptInterface("accessibilityTraversal");
        LinearLayout llParent = findViewById(R.id.llParent);
        llParent.addView(regisetWv, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));

        WebSettings setting = regisetWv.getSettings();

        //设置webview里面的音视频自动播放
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            setting.setMediaPlaybackRequiresUserGesture(false);
        }
        //从Android5.0开始，WebView默认不支持同时加载Https和Http混合模式。设置允许
        //在 X5 内核的 Webview 中，是找不到MIXED_CONTENT_ALWAYS_ALLOW这些参数的，只能手动把值设上去：
        //MIXED_CONTENT_NEVER_ALLOW = 0；
        //MIXED_CONTENT_ALWAYS_ALLOW = 1；
        //MIXED_CONTENT_COMPATIBILITY_MODE = 2；
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.setMixedContentMode(1);
        }
        //https://www.it610.com/article/1294380262372745216.htm  解决android9.0以上的问题
        //需要测试下有什么问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(MainWebActivity.this);
            String packageName = getPackageName();
            if (!packageName.equals(processName)) {
//                WebView.setDataDirectorySuffix(processName);
                android.webkit.WebView.setDataDirectorySuffix(processName);
            }
        }
        setting.setJavaScriptEnabled(true);
        //将图片调整到适合webview的大小
        setting.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        setting.setLoadWithOverviewMode(true);
        // 是否支持画面缩放，默认不支持
        setting.setBuiltInZoomControls(true);
        setting.setSupportZoom(true);
        // 是否显示缩放图标，默认显示
        setting.setDisplayZoomControls(false);
        // 设置网页内容自适应屏幕大小
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setJavaScriptCanOpenWindowsAutomatically(true);
        setting.setDomStorageEnabled(true);
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        setting.setAllowFileAccess(false);
        setting.setAllowFileAccessFromFileURLs(false);
        setting.setAllowUniversalAccessFromFileURLs(false);
        setting.setUserAgentString(regisetWv.getSettings().getUserAgentString() + "/pybapp/"+getVersionName());
        regisetWv.addJavascriptInterface(new MyJavascriptInterface(this), "android");
        WebStorage.getInstance().deleteAllData();//清空H5保存在本地的所有内容；
        registerForContextMenu(regisetWv);
        regisetWv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                //https://openapi.alipay.com/gateway.do?app_id=2017120700430964&method=alipay.trade.wap.pay&format=JSON&charset=utf-8&sign_type=RSA2&timestamp=2019-12-20%2014%3A51%3A55&version=1.0&biz_content=%7B%22body%22%3A%22%E8%B6%A3%E5%8F%A3%E6%89%8D%E8%AF%AD%E8%A8%80%E6%80%9D%E7%BB%B4%E8%AF%BE%E7%A8%8B%E5%8C%85%22%2C%22subject%22%3A%22%E8%B6%A3%E5%8F%A3%E6%89%8D%E8%AF%AD%E8%A8%80%E6%80%9D%E7%BB%B4%E8%AF%BE%E7%A8%8B%E5%8C%85%22%2C%22out_trade_no%22%3A%2220020191220145154935i%22%2C%22total_amount%22%3A%2250.00%22%2C%22product_code%22%3A%22QUICK_WAP_PAY%22%2C%22extend_params%22%3A%7B%22TRANS_MEMO%22%3A%22ch_CSu1yHu1yrP0XzjrLGnHC4G0%22%7D%2C%22time_expire%22%3A%222019-12-21%2014%3A51%22%7D&notify_url=https%3A%2F%2Fnotify.pingxx.com%2Fnotify%2Fcharges%2Fch_CSu1yHu1yrP0XzjrLGnHC4G0&return_url=http%3A%2F%2Ftest.qukoucai.cn%2FUserOrder&sign=asImIp581DJZrT5zYtQ7%2FzzLkSL%2F3GpvBIYRle0bo60IhN%2BmMBWejxkGqNb%2F9ggswAix4foMOixzzxn0qBv26%2FFbOFMwLHVa7BbEOuUCtTPvrK85gpjSTFy9yZ%2FlqIBrIOMkQOO%2FswHs6lHvruvva9i%2B9rZcNLfyc4%2B3VZFH7CI63KuMYKcXlUHhXmru9jvV3iget2JaW8ViTLXNg7cZJIloFEmmd9q%2B7x9s2v780yZgVl5U2S1j8TxwMTtqeDdkWEvrhIdAP4HRl1YXKrGHrpy9bTYuiLZkCJU3IgAc4C0kKVYsOXaiHffGoDIJ04ddWvna16xzfvzokGg8W0NxTA%3D%3D
                //https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx23100341494585f0f0f8812f1912351500&package=1742925728&redirect_url=http%3A%2F%2Ftest.qukoucai.cn%2FUserOrder

                subString(url, "return_url=");
                subString(url, "redirect_url=");

                if (url.startsWith("weixin://wap/pay?") || url.startsWith("wechat")) {
                    try {
                        isToPay = true;
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } catch (Exception e) {
                        // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                        ToastHelper.showToast("该设备没有安装微信");
                        return true;
                    }
                } else if (url.startsWith("alipays://") || url.startsWith("alipay")) {
                    try {
                        isToPay = true;
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } catch (Exception e) {
                        // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                        // 启动支付宝 App 失败，会自行跳转支付宝网页支付
                        return true;
                    }
                }

                // 处理微信 H5 支付跳转时验证请求头 referer 失效
                // 验证不通过会出现“商家参数格式有误，请联系商家解决”
                if (url.contains("wx.tenpay.com")) {

                    // 申请微信 H5 支付时填写的域名
                    // 比如经常用来测试网络连通性的 http://www.baidu.com

                    // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
                    if (("4.4.3".equals(Build.VERSION.RELEASE))
                            || ("4.4.4".equals(Build.VERSION.RELEASE))) {
                        if (firstVisitWXH5PayUrl) {
                            view.loadDataWithBaseURL(referer, "<script>window.location.href=\"" + url + "\";</script>",
                                    "text/html", "utf-8", null);
                            // 修改标记位状态，避免循环调用
                            // 再次进入微信H5支付流程时记得重置状态 firstVisitWXH5PayUrl = true
                            firstVisitWXH5PayUrl = false;
                        }
                        // 返回 false 由系统 WebView 自己处理该 url
                        return false;
                    } else {
                        // HashMap 指定容量初始化，避免不必要的内存消耗
                        HashMap<String, String> map = new HashMap<>(1);
                        map.put("Referer", referer);
                        view.loadUrl(url, map);
                        return true;
                    }
                } else {
//                    view.loadUrl(url);
//                    return true;
                    return super.shouldOverrideUrlLoading(view,url);
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在 android 6.0才出现
//                int statusCode = errorResponse.getStatusCode();
//                if (404 == statusCode || 500 == statusCode) {
//                    view.loadUrl("about:blank");// 避免出现默认的错误界面
//                    llNetworkFailed.setVisibility(View.VISIBLE);
//                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                // 不要调用super.onReceivedSslError，因为其包含了一条 handler.cancel()，第一次访问时无法加载，第二次以后可以加载
                // super.onReceivedSslError(view, handler, error);
                // 忽略SSL证书错误，继续加载页面
                handler.proceed();
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {//是否是为 main frame创建
                    webView.loadUrl("about:blank");// 避免出现默认的错误界面
                    llNetworkFailed.setVisibility(View.VISIBLE);
                }
            }
        });
        String url = getIntent().getStringExtra("url");
        regisetWv.loadUrl(url);

        tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean mobileConnected = NetUtil.isNetworkAvailable(MultiDexApplication.sContext);
                if (mobileConnected) {
                    llNetworkFailed.setVisibility(View.GONE);
                    regisetWv.loadUrl(url);
                } else {
                    ToastHelper.showToast("网络未连接，请检查网络状态");
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        regisetWv.setWebChromeClient(new MyChromeWebClient());
    }

    /** 视频全屏参数 */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private IX5WebChromeClient.CustomViewCallback customViewCallback;
    /** 视频播放全屏 **/
    private void showCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        getWindow().getDecorView();

        FrameLayout decor = (FrameLayout)   getWindow().getDecorView();
        fullscreenContainer = new  FullscreenHolder(this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }
    private String getVersionName()  {
        // 获取packagemanager的实例
        PackageManager packageManager =  getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo( getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo==null)
            return "";
        else
        return packageInfo.versionName;
    }
    /** 隐藏视频全屏 */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        regisetWv.setVisibility(View.VISIBLE);
        setStatusBarVisibility(true);
    }
    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    /** 全屏容器界面 */
    static class FullscreenHolder extends FrameLayout {

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }
    }
    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    private void subString(String url, String target) {
        if (url.contains(target)) {
            String substring = url.substring(url.indexOf(target) + target.length(), url.length());
            if (substring.contains("&")) {
                String ss = substring.substring(0, substring.indexOf("&"));
                return_url = Uri.decode(ss);
            } else {
                return_url = Uri.decode(substring);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        regisetWv.reload();
        if (isToPay && !TextUtils.isEmpty(return_url)) {
            regisetWv.loadUrl(return_url);
            return_url = "";
            isToPay = false;
        }
        if (audioManager != null) {
            audioManager.abandonAudioFocus(listener);
            audioManager = null;
        }
        if (regisetWv != null) {
            regisetWv.onResume();
        }
    }

    public class MyChromeWebClient extends WebChromeClient {
        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
            super.onShowCustomView(view, customViewCallback);
            showCustomView(view,customViewCallback);
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            hideCustomView();
        }

        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        // For Android 5.0+
        @RequiresApi(api = Build.VERSION_CODES.M)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            checkSelfPermission(Manifest.permission.CAMERA);
            checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            //申请权限
            classrequestPermission();
            return true;
        }
    }

    /**
     * 拍照或选择相册
     */
    private void takePhoto() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainWebActivity.this);
        alertDialog.setTitle("选择");
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setItems(new CharSequence[]{"拍照", "录视频", "相册"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            openCamera();
                        } else if (which == 1) {
                            recordVideo();
                        } else {
                            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                            i.addCategory(Intent.CATEGORY_OPENABLE);
                            i.setType("image/*,video/*");
                            startActivityForResult(Intent.createChooser(i, "File Browser"), PHOTO_REQUEST);
                        }
                    }
                });
        alertDialog.show();
    }

    /**
     * 录像
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
//        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }

    private void openCamera() {
        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
        imageUri = Uri.fromFile(fileUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(MainWebActivity.this, SkinApplication.getInstance().getPackageName() + ".provider", fileUri);
        } else {
            imageUri = Uri.fromFile(fileUri);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    /**
     * 保存图片的权限申请
     */
    private void saveImgRequestPermission() {
        XXPermissions.with(this)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //toast("获取权限成功");
                            executeSaveImg();
                        } else {
                            //"获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            //toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(SkinApplication.getInstance(), permissions);
                        } else {
                            //toast("获取权限失败");
                        }
                    }
                });
    }

    /**
     * 点击取消的回调
     */
    private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
        }
    }

    /**
     * 权限申请
     */
    private void classrequestPermission() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //toast("获取权限成功");
                            takePhoto();
                        } else {
                            //"获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            //toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(SkinApplication.getInstance(), permissions);
                        } else {
                            //toast("获取权限失败");
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST || requestCode == VIDEO_REQUEST) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
        if (requestCode == SHUAXIN && resultCode == RESULT_OK){
            regisetWv.reload();
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    }

    public class JSInterestInterface {
        //JSInterestInterface.saveImg(base64图片)
        @JavascriptInterface
        public void saveImg(String base64DataStr) {
            if (TextUtils.isEmpty(base64DataStr)) {
                Toast.makeText(MainWebActivity.this, "图片地址无效", Toast.LENGTH_SHORT).show();
                return;
            }
            mBase64DataStr = base64DataStr;
            saveImgRequestPermission();
        }
    }


    /**
     * 执行保存图片的操作
     */
    private void executeSaveImg() {
        // 1.去掉base64中的前缀
        String base64Str = mBase64DataStr.substring(mBase64DataStr.indexOf(",") + 1, mBase64DataStr.length());
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "interest");// "abc":图片保存的文件夹的名称
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // 2.拼接图片的后缀，根据自己公司的实际情况拼接，也可从base64中截取图片的格式。
        String imgName = System.currentTimeMillis() + ".png";
        File fileTest = new File(appDir, imgName);
        // 3. 解析保存图片
        byte[] data = Base64.decode(base64Str, Base64.NO_PADDING);

        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                data[i] += 256;//调整异常数据
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(fileTest);
            os.write(data);
            os.flush();
            os.close();

            // 4. 其次通知系统刷新图库
            updateAlbum(fileTest);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(MainWebActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(MainWebActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 通知图库更新数据
     * file
     */
    private void updateAlbum(File file) {
        // 最后通知图库更新
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        Toast.makeText(MainWebActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void h5finish() {
        finish();
    }

    @Override
    protected void onPause() {
        //解决退出时音效继续播放
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        listener = new AudioManager.OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
            }
        };
        audioManager.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        super.onPause();
        if (regisetWv != null) {
            regisetWv.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (regisetWv != null && regisetWv.getParent() != null) {
            ((ViewGroup) regisetWv.getParent()).removeView(regisetWv);
            regisetWv.resumeTimers();
            regisetWv.destroy();
            regisetWv = null;
            ViewGroup view = (ViewGroup) getWindow().getDecorView();
            view.removeAllViews();
        }
    }

}